package sq.service.impl;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sq.dao.User;
import sq.repository.UserRepository;
import sq.repository.VerificationRepository;
import sq.service.AuthenticationService;
import sq.service.VCodeValidationService;
import sq.vo.BaseRespVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.Date;

/**
 * 开发者用户注册,登录,注销接口实现类
 *
 * @author sunquan
 */
@Service
@Transactional
public class AuthenticationServiceImpl implements AuthenticationService {
    private static final Logger log = LoggerFactory.getLogger(AuthenticationServiceImpl.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private VCodeValidationService vCodeValidationService;
    @Autowired
    private VerificationRepository verificationRepository;

    /**
     * 注册接口实现类
     *
     * @param username      开发者用户名
     * @param password     开发者密码
     * @param phone        开发者手机号
     * @param verification 手机验证码(用户输入)
     * @return UserVO      API应答接口类
     */
    @Override
    public BaseRespVO<User> auth(String username, String password, String phone, String verification) {
        User user = userRepository.findUserByUsernameOrPhone(username,phone);
        BaseRespVO<User> baseRespVO = null;
        if (user == null) {
            Integer flag = vCodeValidationService.vCodeValidated(verification, phone);
            if (flag < 0) {//短信验证成功
                User userCreate = new User(username,password, phone, new Date(), "user");
                userRepository.save(userCreate);
                baseRespVO = new BaseRespVO<User>("0", "auth successful", userCreate);
            } else if (flag == 0) {
                baseRespVO = new BaseRespVO<User>("2", "print validationCode lose");
            } else if (flag == 1) {
                baseRespVO = new BaseRespVO<User>("3", "the validationCode is out of expireTime");
            } else if (flag == 2) {
                baseRespVO = new BaseRespVO<User>("4", "Client has lost validationCode,please try it again");
            }
        } else {
            baseRespVO = new BaseRespVO<User>("1", "register failure ,the user has exist");
        }
        verificationRepository.deleteByPhone(phone);
        return baseRespVO;
    }

    /**
     * 注销接口实现类
     *
     * @param request http请求
     */
    @Override
    public void unAuth(HttpServletRequest request) {
        //清除Session
        HttpSession session = request.getSession(false);
        //session失效
        session.invalidate();
    }

    /**
     * 判断session是否存在
     * @param request
     * @return
     */
    @Override
    public boolean sessionExists(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session.getAttribute("userSession")==null||session.getAttribute("userSession")==""){
            return false;
        }
        else{
            return true;
        }

    }




    /**
     * @param username  开发者账户
     * @param password 开发者用户密码
     * @param request  Http请求
     * @return User Session中的实体类
     */
    @Override
    public User loginService(String username, String password, HttpServletRequest request) {
        User user = userRepository.findUserByUsernameOrPhone(username, username);
        //添加Session
        HttpSession session = request.getSession();
        session.setAttribute("userSession",user.getUsername());
        return user;
    }

    @Override
    public Integer retuenUserId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
            String userName = session.getAttribute("userSession").toString();
            User user = userRepository.findUserByUsername(userName);
            Integer userId = user.getUserId();
            return userId;
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User returnUser(Integer userId) {
        User user = userRepository.findOne(userId);
        return user;
    }
}




